﻿using System.IO;
using System.Security.Cryptography;

namespace xshare
{


    public static class MD5Utils
    {
        //public static readonly MD5 MD5 = MD5.Create();


        public static string FileMD5(string filePath, MD5 md5)
        {
            using (var fs = new FileStream(filePath, FileMode.Open))
            {
                return StreamMD5(fs, md5);
            }
        }

        public static string StreamMD5(Stream s, MD5 md5)
        {
            if (null == md5)
                md5 = MD5.Create();

            using (s)
            {
                var md5Bytes = md5.ComputeHash(s);
                return Bytes2HexString(md5Bytes);
            }
        }


        public static string StringMD5(string utf8String, MD5 md5)
        {
            if (null == md5)
                md5 = MD5.Create();

            var strBytes = System.Text.Encoding.UTF8.GetBytes(utf8String);
            var md5Bytes = md5.ComputeHash(strBytes);
            return Bytes2HexString(md5Bytes);
        }


        public static string Bytes2HexString(byte[] bytes)
        {
            var sb = StringUtils.Builder;

            for (int i = 0; i < bytes.Length; ++i)
                sb.Append(bytes[i].ToString("x2"));

            return sb.BuildString();
        }
        /*
        public static string Bytes2HexString(byte[] bytes)
        {
            // BitConverter可以直接帮我们把byte数组转为字符串
            return BitConverter.ToString(bytes).Replace("-", "");
        }
        */


        /*
        public static string Bytes2HexString(byte[] bytes)
        {
            char[] Hex_Chars = {'0','1','2','3','4','5','6','7','8','9','A','B','C','D','E','F'};
            
            var sb = StringUtils.Builder;
            for (int i = 0; i < bytes.Length; ++i)
            {
                var b = bytes[i];
                sb.Append(Hex_Chars[b >> 4 & 0xf]);
                sb.Append(Hex_Chars[b & 0xf]);
            }

            var str = sb.ToString();
            sb.Clear();
            return str;
        }
        */
        
    } //end of class


}
